$(document).ready(function(){
	
	$( "#countDate" ).datepicker({ minDate: -30, maxDate: +0 });
	
	$("#countDate").change(function(){
		$.getJSON(getRootPath()+ "/MainMenu/profit/totalSelledAmount.htm",{ countDate : $("#countDate").val()},function(data){
			$("#yesterSelledAmount").val(data.sum);
		});
		
		$.getJSON(getRootPath()+ "/MainMenu/profit/shouldReturnProfitMemberCount.htm",{ countDate : $("#countDate").val()},function(data){
			$("#shouldReturnProfitMemberCount").val(data.shouldReturnProfitMemberCount);
			
			var amount = $("#yesterSelledAmount").val();
			var percent = $("#profitReturnPercent").val();
			var count = $("#shouldReturnProfitMemberCount").val();
			var totalReturnProfit=accMul(amount,accDiv(percent,100));
			$("#avgReturnProfitAmount").val(forDight(accDiv(totalReturnProfit,count),2));
			$("#totalProfitAmount").val(forDight(totalReturnProfit,2));
		});
		
		if($("#profitTable").text().length>6){
			$("#profitTable").html("统计日期已经被修改，请重新生成返利表。");
		}
	});
	
	$("#generateBtn").click(function(){
		
		var selledAmount = $("#yesterSelledAmount").val();
		var returnPercent = $("#profitReturnPercent").val();
		if(isNaN(selledAmount) || isNaN(returnPercent)){
			alert("只能输入数字，请检查");
			return;
		}
		
		if($("#yesterSelledAmount").val()==""){
			alert("昨日销售额不能为空");
			return;
		}
		
		if($("#countDate").val()==""){
			alert("统计日期不能为空");
			return;
		}
		
		if($("#profitReturnPercent").val()==""){
			alert("返利比例不能为空");
			return;
		}
		
		var shouldReturnProfitMemberCount= $("#shouldReturnProfitMemberCount").val();
		if(isNaN(shouldReturnProfitMemberCount) || shouldReturnProfitMemberCount==0){
			alert("返利会员数为0，不能生产返利表");
			return;
		}
		$("#profitTable").load(getRootPath()+ "/MainMenu/profit/generateProfitTable.htm",$("#profitForm").serializeArray());
	});
	
	$("#calcBtn").click(function(){
		var amount = $("#yesterSelledAmount").val();
		var percent = $("#profitReturnPercent").val();
		var count = $("#shouldReturnProfitMemberCount").val();
		
		if(isNaN(amount) || isNaN(percent) || isNaN(count)){
			alert("只能输入数字，请检查");
			return;
		}
		
		var totalReturnProfit=accMul(amount,accDiv(percent,100));
		$("#avgReturnProfitAmount").val(forDight(accDiv(totalReturnProfit,count),2));
		$("#totalProfitAmount").val(forDight(totalReturnProfit,2));
	});
	
	
	$("#editAmountDialog").dialog({
		modal:true,
		height:80,
		resizable:false,
		autoOpen:false,
		close:function(){
			$("#newAmount").val("");
		}
	});
});